// 针对公共组件 public/components/function/model/common/cfgModelCrud.vue 的配置
import cfgCrudModal from 'public/components/configComp/basic/cfgCrud/cfgCrud-modal'
import cfgCrudAddModal from 'public/components/configComp/basic/cfgCrud/cfgCrud-AddModal'

export default {
    components: { cfgCrudAddModal, cfgCrudModal },
    data() {
      let data = this.tools.lodash.merge({
        modelName: `${this.prefix}`,
        classObject: null,
        collectionObject: null,
        modelList: [],
        loading: false,
        modalNeedQuery: true,
        pageSizeOpts: [10, 30, 50, 100],
        pageNavigation: { total: 0, pageSize: 30, pageNumber: 1 },
        modalConfig: {
            hasFeatures: true,
            labelWidth: 90,
        },
        modelDrawer: {
          status: 'new',
          show: false
        },
        tableConfig: {
          search: true,
          addButton: true,
          actionEdit: true,        // 显示编辑按钮, 默认为true
          actionDetail: true,      // 显示查看按钮, 默认为true
          actionDelete: true,      // 显示删除按钮, 默认为true
          batchDeleteButton: true, // 显示批量删除按钮
          downloadIcon: true,
          uploadIcon: true,
          uploadUrl: '/',
          tableSizeIcon: true,
          fullscreenIcon: true,
          refreshIcon: true,
          columnSettingIcon: true,
          action: true,
          actionOption: { // action的配置
            // width: 200,
            // fixed: 'right',
            // align: 'center',
          },
          actionButtons: [],   // action追加的button
          additionalAction: {  // 附加操作的配置，以及button列表
            show: true,
            // width: 120,
            buttons: [
              // {
              //     title: { 'zh-CN': '编辑JSON', 'en-US': 'edit json' }, color: 'green',
              //     eventName: 'actionEditJson'
              // }
            ]
          }
        },
        expandColumns: {
          type: 'expand',
          slot:'expand',
          width: 40,
          render: (h, params) => {
            return h('div', [
                h('div', this.$t(`model.comments`) + ': '),
                h('div',params.row.comments),
                h('div', this.$t(`model.version`) + `: ${params.row.version}`),
                h('div', this.$t(`model.published`) + `: ${params.row.published}`),
                h('div', this.$t(`model.createTime`) + `: ${params.row.createTime || ''}`),
                h('div', this.$t(`model.updateTime`) + `: ${params.row.updateTime || ''}`),
            ])
          }
        },
        isReset: false,
      }, this.config)
      return data
    },
    methods:{
      async loadPage(pageNavigation, filter = {}) {
        filter = this.isReset ? filter : {...filter, ...this.searchData}
        let condition=this.collectionObject.util.getFilter(filter, 'like')
  
        this.loading = true;
        let flag = await this.collectionObject.queryInfoByPage(pageNavigation.pageNumber, pageNavigation.pageSize, condition)
  
        this.isReset = false
        if (flag) {
          this.pageNavigation.total = this.collectionObject.total;
          this.dataChange('query', this.collectionObject.records)
          this.loading = false;
        } else {
          this.loading = false;
        }
      },
      handleSearch(filter) {
        this.pageNavigation.pageNumber = 1;
        this.loadPage(this.pageNavigation, filter)
      },
      handleReset() {
        this.isReset = true
        this.pageNavigation.pageNumber = 1;
        this.loadPage(this.pageNavigation)
      },
      async getRecord(filter) {
        let flag = await this.classObject.query(this.collectionObject.util.getFilter(filter))
        return flag
      },
      async deleteRecord(classNames) {
        this.loading = true;
        let flag= await this.collectionObject.deleteByClassNames(classNames)
  
        this.clearTableSelection(flag)
        this.dataChange('delete')
        this.loading = false;
        return flag
      },
      async deleteRecordByIds(ids) {
        this.loading = true;
        let flag= await this.collectionObject.deleteByIds(ids)
  
        this.clearTableSelection(flag)
        this.dataChange('delete')
        this.loading = false;
        return flag
      },
      async handleNewAddSubmit() {
        this.loading = true;
        if (await this.classObject.add()) {
          this.collectionObject.addRecord(this.classObject.record);
          this.dataChange('add')
          this.loading = false;
          this.modelDrawer.show = false
          return true
        } else {
          this.loading = false;
          return false
        }
      },
      async handleEditSubmit() {
        this.loading = true;
        let flag = await this.classObject.updateById()
        if (flag) {
          this.collectionObject.updateRecord(this.classObject.record)
          this.dataChange('edit')
          this.loading = false;
          this.modelDrawer.show = false
        } else {
          this.loading = false;
        }
      },
      handleCreate() {
        this.classObject.setRecord()
        console.log("file: modelMixin.js:141  handleCreate  this.classObject:", this.classObject)
        this.modelDrawer.status = 'new'
        this.modelDrawer.show = true
      },
      async handleEdit(row, index) {
        let filter = this.modalConfig.isInstance || this.tableConfig.queryById ? {id: row.id} : { type: row.type, className: row.className }
        if (this.tableConfig.editBtnAction) {
          this[this.tableConfig.editBtnAction](row, index)
          return
        }
        this.loading = true;
        this.modelDrawer.status = 'edit'
  
        if (!this.modalNeedQuery) {
          this.classObject.setRecord(row)
          this.modelDrawer.show = true
          this.loading = false
        } else if (await this.getRecord(filter)) {
          this.modelDrawer.show = true
          this.loading = false;
        } else {
          this.loading = false;
        }
      },
      async handleDetail(row, index) {
        let filter = this.modalConfig.isInstance || this.tableConfig.queryById ? {id: row.id} : { type: row.type, className: row.className }
        this.loading = true;
        this.modelDrawer.status = 'read'
  
        if (!this.modalNeedQuery) {
          this.classObject.setRecord(row)
          this.modelDrawer.show = true
          this.loading = false
        }
        else if (await this.getRecord(filter)) {
          this.modelDrawer.show = true
          this.loading = false;
        } else {
          this.loading = false;
        }
      },
      handleDelete(row, index) {
        console.log('handleDelete', this.deleteById);
        if (this.deleteById) {
          this.deleteRecordByIds([row.id])
        } else if (this.modalConfig.isInstance) {
          this.deleteRecordByInstanceId([row.instanceId])
        } else {
          this.deleteRecord([row.className])
        }
      },
      async handleDeleteMultiple(selection) {
        if (this.deleteById) {
          await this.deleteRecordByIds(selection.map(item => item.id))
        } else if (this.modalConfig.isInstance) {
          await this.deleteRecordByInstanceId(selection.map(item => item.instanceId))
        } else {
          await this.deleteRecord(selection.map(item => item.className))
        }
      },
      clearTableSelection(flag) {
        flag && (this.$refs.table.selection = [])
      },
      dataChange(type) {
        this.$emit('dataChange', type)
      },
    },
    created() {
      this.collectionObject = this.$modelObject.create(`${this.modelName}Collection`);
      this.classObject = this.$modelObject.create(this.modelName)
      // console.log("file: modelMixin.js:220  created  this.modelName:", this.modelName, this.classObject)
    },
    beforeMount() {
      let filter = {}
      if (this.searchHistory) {
        filter = window.localStorage.getItem(`plat_${this.searchHistory}_searchObj`)
        filter = filter ? JSON.parse(filter) : {}
      }
      this.loadPage(this.pageNavigation, filter)
    },
    props:{
      title:{
        type:String
      },
      type:{
        type:String
      },
      prefix:{
        type:String
      },
      config: {
        default() {
          return {}
        }
      },
      searchData: {
        default() {
          return {}
        }
      },
      isPointer: {
        type: Boolean
      }
    },
    computed: {
      columns() {
        return [
          {
            key: 'type',
            title: {
              'zh-CN': '模型类型',
              'en-US': 'model type'
            }[this.G_Locale],
            minWidth: 100,
            align: 'center',
            show: true,
          },
          {
            key: 'className',
            title: {
              'zh-CN': '模型名称',
              'en-US': 'model name'
            }[this.G_Locale],
            minWidth: 100,
            align: 'center',
            show: true
          },
          {
            key: 'version',
            title: {
              'zh-CN': '版本号',
              'en-US': 'version'
            }[this.G_Locale],
            minWidth: 50,
            align: 'center',
            show: true,
          },
          {
            key: 'published',
            title: {
              'zh-CN': '是否发布',
              'en-US': 'published'
            }[this.G_Locale],
            minWidth: 50,
            align: 'center',
            show: true
          },
          {
            key: 'createTime',
            title: {
              'zh-CN': '创建时间',
              'en-US': 'create time'
            }[this.G_Locale],
            minWidth: 112,
            // width: 200,
            align: 'center',
            show: true,
          },
          {
            key: 'updateTime',
            title: {
              'zh-CN': '更新时间',
              'en-US': 'update time'
            }[this.G_Locale],
            minWidth: 112,
            // width: 200,
            align: 'center',
            show: true,
          },
        ]
      },
      queryFormItem() {
        let item=[
          {
            key: 'type',
            title: {
              'zh-CN': '所属类型',
              'en-US': 'type'
            }[this.G_Locale],
            config: {
              type: 'text',
              clearable: true,
            }
          },
          {
          key: 'className',
          title: {
            'zh-CN': '模型类名',
            'en-US': 'class name'
          }[this.G_Locale],
          config: {
            type: 'text',
            clearable: true,
          }
        }]
        return item;
      },
      // 新增、查看、编辑弹窗，表单展示的字段
      modalFormItem() {
        let items = [
            {
                key: 'type',
                title: this.$t(`model.type`),
                config: {
                    type: 'text',
                    clearable: true,
                },
                editConfig: {
                    disabled: true
                },
                rules: [
                    { required: true,
                      trigger: 'blur',
                      message: this.$t(`model.type`)+this.$t(`global.notEmpty`)
                    },
                ]
            },
            {
                key: 'className',
                title: {
                    'zh-CN': '模型类名',
                    'en-US': 'class name'
                }[this.G_Locale],
                config: {
                    type: 'text',
                    maxlength: 50,
                    clearable: true,
                    placeholder: {
                        'zh-CN': '请输入模型类名',
                        'en-US': 'please input class name'
                    }[this.G_Locale]
                },
                editConfig: {
                    disabled: true
                },
                rules: [
                    { required: true, trigger: 'blur',
                        message: { 'zh-CN': '模型类名不能为空', 'en-US': 'The class name cannot be empty' }[this.G_Locale]
                    }
                ]
            },
            {
                key: 'comments',
                title: {
                    'zh-CN': '说明',
                    'en-US': 'comments'
                }[this.G_Locale],
                span: 24,
                config: {
                    type: 'textarea',
                    autosize: {minRows: 1, maxRows: 5},
                    clearable: true,
                    placeholder: {
                        'zh-CN': '请输入说明',
                        'en-US': 'please input comments'
                    }[this.G_Locale],
                }
            },
        ]
        return items
      },
      collapseFormItem() {
        return this.queryFormItem
      },
      additionalAction() {
        let buttons = []
        let action = this.tableConfig.additionalAction;
  
        if (!action || !action.show || !action.buttons || !action.buttons.length) {
          return { show: false }
        }
  
        action.buttons.forEach(item => {
          item.title = item.title[this.G_Locale]
          item.event = (row, index) => {
            let res = ''
            if (item.eventName && this[item.eventName]) {
              res = this[item.eventName](row, index)
            }
            if (item.triggerName) {
              res = this.$emit(item.triggerName, item, row, index)
            }
            return res;
          }
          buttons.push(item)
        })
  
        return {
          key: 'additionalAction',
          title: { 'zh-CN': '附加操作', 'en-US': 'addition action' }[this.G_Locale],
          slot: 'additionalAction',
          width: 280,
          fixed: 'right',
          align: 'center',
          ...action,
          buttons
        }
      },
      actionButtonsCalc() {
        let buttons = [];
        let actionButtons = this.tableConfig.actionButtons
  
        if (this.tableConfig.action && actionButtons && actionButtons.length) {
          actionButtons.forEach(item => {
            let newItem = {...item}
            newItem.title = item.title[this.G_Locale]
            newItem.event = (row, index) => {
              let res = ''
              if (item.eventName && this[item.eventName]) {
                res = this[item.eventName](row, index)
              }
              if (item.triggerName) {
                res = this.$emit(item.triggerName, item, row, index)
              }
              return res;
              // return item.eventName && this[item.eventName] ? this[item.eventName](row, index) : ''
            }
            buttons.push(newItem)
          })
        }
        return buttons
      },
      lang() {
        return {
          "en-US": {
            type: 'type',
            className: 'class name',
            instanceName: 'instance name',
            category: 'category',
            eventName: 'event name',
            comments: 'comments',
            version:'version',
            published:'published',
            createTime:'createTime',
            updateTime:'updateTime'
          },
          "zh-CN": {
            type: '所属类型',
            className: '模型类名',
            instanceName: '实例名',
            category: '分类',
            eventName: '事件名称',
            comments:'注释',
            version:'版本',
            published:'已发布',
            createTime:'创建时间',
            updateTime:'更新时间'
          },
        }[this.G_Locale]
      },
      typeList() {
          return this.$modelObject.getModelType(this.modelName.replace('Model', ''));
      },
    },
}
